package org.sninwo.lnbook.book.web;

import java.io.File;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.sninwo.lnbook.base.BaseAction;
import org.sninwo.lnbook.base.Page;
import org.sninwo.lnbook.book.entity.Book;
import org.sninwo.lnbook.book.entity.BookType;
import org.sninwo.lnbook.book.service.BookImportManager;
import org.sninwo.lnbook.book.service.BookManager;
import org.sninwo.lnbook.uitls.LnBookUtils;
import org.sninwo.lnbook.uitls.WebUtils;

@Namespace("/admin")
public class BookAction extends BaseAction {
	public static final String BOOK_GUIDE_FILE_PATH = "resources/book-guide.txt";
	private static final long serialVersionUID = 4628858679559929335L;
	public Book book = new Book();
	public long bookId;
	public Page<Book> page = new Page<Book>(25);
	
	public File upload;
	public String uploadEncoding = "GBK";
	public String uploadContentType;
	
	public String bookGuide;
	
	@Resource BookManager bookMgr;
	@Resource BookImportManager bookImportMgr;
	
	public String get(){
		Book book = bookMgr.getBook(bookId);
		BookType type = bookMgr.getBookType(book.getTypeId());
		return json("book", book, "type", type);
	}
	
	public String save(){
		bookMgr.saveBook(book);
		return successJson();
	}
	
	public String remove(){
		bookMgr.removeBooks(ids);
		return successJson();
	}
	
	public String query(){
		Page<Book> p = bookMgr.queryBook(page, book);
		return json(p.toMap());
	}
	
	@SuppressWarnings("unchecked")
	public String import_() throws Exception{
		if (!uploadContentType.equals("text/plain")){
			LnBookUtils.throwError("上传的文件必须为文本文件！");
		}
		List<String> lines = FileUtils.readLines(upload, uploadEncoding);
		String msg = bookImportMgr.doImport(lines);
		/**
		 * 用Ext结合struts2上传文件会有一个诡异的问题：
		 * 返回json时，如果contentType设置为application/json，浏览器会提示下载文件，
		 * 必须将contentType设置为text/html，然后直接输出json
		 */
		WebUtils.getResponse().setContentType("text/html");
		return output(LnBookUtils.toExtSuccessJson(msg));
	}
	
	/**
	 * 保存凡例
	 */
	public String saveBookGuide() throws Exception{
		File file = new File(WebUtils.getRealPath(BOOK_GUIDE_FILE_PATH));
		FileUtils.writeStringToFile(file, bookGuide.trim(), "utf-8");
		return successJson();
	}

	/**
	 * 获取凡例
	 */
	public String getBookGuide() throws Exception{
		File file = new File(WebUtils.getRealPath(BOOK_GUIDE_FILE_PATH));
		if (!file.exists()){
			return text("");
		}
		String bookGuide = FileUtils.readFileToString(file, "utf-8");
		return text(bookGuide);
	}
}
